# _*_coding:utf-8_*_

from django.utils import timezone
from django.db.models import Count
import time

def get_orderby(request, model_objs, admin_form):
    orderby_field = request.GET.get('orderby')
    print('======== orderby_field ======',type(orderby_field))

    if  orderby_field:
        orderby_field = orderby_field.strip()
        orderby_column_index = admin_form.list_display.index(orderby_field.strip('-'))
        objs = model_objs.order_by(orderby_field)
        # print("orderby",orderby_field)
        if orderby_field.startswith('-'):
            orderby_field = orderby_field.strip('-')

        else:
            orderby_field = '-%s' % orderby_field

        return [objs, orderby_field, orderby_column_index]

    else:
        return [model_objs, orderby_field, None]


class TableHandler(object):
    def __init__(self, request, model_class, admin_class, query_sets, order_res):
        self.request = request
        self.model_class = model_class
        # self.admin_class = admin_class
        self.query_sets = query_sets
        # self.choice_fields = admin_class.choice_fields or ''
        self.fk_fields = admin_class.fk_fields

        self.list_display = admin_class.list_display
        self.list_filter = self.get_list_filter(admin_class.list_filter)

        # for order by
        self.orderby_field = order_res[1]
        self.orderby_col_index = order_res[2]

        # print("list display:",admin_class.list_display)

        #for dynamic display
        self.dynamic_fk = getattr(admin_class,'dynamic_fk') if \
                hasattr(admin_class, 'dynamic_fk') else None
        self.dynamic_list_display = getattr(admin_class,'dynamic_list_display') if \
            hasattr(admin_class,'dynamic_list_display') else ()
        self.dynamic_choice_fields = getattr(admin_class,'dynamic_choice_fields') if \
            hasattr(admin_class,'dynamic_choice_fields') else ()

        #for m2m fields
        self.m2m_fields  = getattr(admin_class,'m2m_fields') if \
            hasattr(admin_class,'m2m_fields') else ()

    def get_list_filter(self, list_filter):
        filters = []
        # print("list filters",list_filter)
        for i in list_filter:
            col_obj = self.model_class._meta.get_field(i)
            # print("=====col obj=====", col_obj )
            # =====col obj===== repository.SessionTrack.user
            # =====col obj===== repository.SessionTrack.bind_host
            # =====col obj===== repository.SessionTrack.date

            # print("=====col obj=====", col_obj.deconstruct() )
            # =====col obj===== ('user', 'django.db.models.ForeignKey', [], {'on_delete': <function CASCADE at 0x000001C93B5A0048>, 'to': 'repository.UserProfile'})
            # =====col obj===== ('bind_host', 'django.db.models.ForeignKey', [], {'on_delete': <function CASCADE at 0x000001C93B5A0048>, 'to': 'repository.BindHosts'})
            # =====col obj===== ('date', 'django.db.models.DateTimeField', [], {'auto_now_add': True})

            data = {
                'verbose_name': col_obj.verbose_name,
                'column_name': i,
                # 'choices' : col_obj.get_choices()
            }

            if col_obj.deconstruct()[1] not in ('django.db.models.DateTimeField',):
                try:
                    choices = col_obj.get_choices()
                    print('===1.choice===',choices)

                    # ===1.choice=== [('', '---------'), (1, '1779038564@qq.com')]
                    # ===1.choice=== [('', '---------'), (1, '192.168.3.100-root(ssh/password)123qwe'), (2, '10.0.133.246-root(ssh/password)111qqq,,,'),]

                except AttributeError as e:  # get_choices 处理没有 多个选项的时候。
                    choices_list = col_obj.model.objects.values(i).annotate(count=Count(i))
                    print('===2.choices_list===', choices_list)
                    choices = [[obj[i], obj[i]] for obj in choices_list]
                    print('===3.choice===',choices)
                    choices.insert(0, ['', '----------'])


            else:  # 特殊处理datefield 和 DateTimeField  此处请注意的是 数据库里models 的字段的类型。datefield 或者 DateTimeField
                today_obj = timezone.datetime.now()
                choices = [
                    ('', '---------'),
                    (today_obj.strftime("%Y-%m-%d"), '今天'),
                    ((today_obj - timezone.timedelta(days=7)).strftime("%Y-%m-%d"), '过去7天'),
                    ((today_obj - timezone.timedelta(days=today_obj.day)).strftime("%Y-%m-%d"), '本月'),
                    ((today_obj - timezone.timedelta(days=90)).strftime("%Y-%m-%d"), '过去3个月'),
                    ((today_obj - timezone.timedelta(days=180)).strftime("%Y-%m-%d"), '过去6个月'),
                    ((today_obj - timezone.timedelta(days=365)).strftime("%Y-%m-%d"), '过去1年'),
                    ((today_obj - timezone.timedelta(seconds=time.time())).strftime("%Y-%m-%d"), 'ALL'),
                ]
            data['choices'] = choices
            # print(choices)
            # handle selected data
            if self.request.GET.get(i):
                data['selected'] = self.request.GET.get(i)
            filters.append(data)

        print(filters)

        # [
        #   {
        #    'column_name': 'user', 'verbose_name': 'user', 'choices': [('', '---------'), (1, '1779038564@qq.com')]
        #   },
        #
        #   {
        #        'column_name' : 'bind_host',
        #        'verbose_name': 'bind host',
        #        'choices': [
        #                    ('', '---------'), (1, '192.168.3.100-root(ssh/password)'), (2, '10.0.133.246-root(ssh/password)'),
        #                    (3, '192.168.3.101-root(ssh/password)'), (4, '192.168.3.102-root(ssh/password)')
        #                    ]
        #    },
        #
        #    {
        #     'column_name': 'date',
        #     'verbose_name': 'date',
        #     'choices': [
        #                 ('', '---------'), ('2017-08-17', '今天'), ('2017-08-10', '过去7天'), ('2017-07-31', '本月'),
        #                 ('2017-05-19', '过去3个月'), ('2017-02-18', '过去6个月'), ('2016-08-17', '过去1年'), ('1970-01-01', 'ALL')
        #                ]
        #    }
        #  ]

        return filters


def table_filter(request, model_admin, models_class):
    '''根据过滤条件查找数据'''

    print(model_admin.list_filter)
    filter_conditions = {}
    for condition in model_admin.list_filter:
        if request.GET.get(condition):
            filed_type_name = models_class._meta.get_field(condition).__repr__()
            print('==filed_type_name==',filed_type_name)
            # ==filed_type_name== <django.db.models.fields.related.ForeignKey: user>

            if 'ForeignKey' in filed_type_name:
                filter_conditions['%s_id' % condition] = request.GET.get(condition)
            elif 'DateField' in filed_type_name or 'DateTimeField' in filed_type_name:
                filter_conditions['%s__gt' % condition] = request.GET.get(condition)
            else:
                filter_conditions[condition] = request.GET.get(condition)

    # print("=====filter conditons======", filter_conditions)
    # 结果：
    # =====filter conditons====== {'bind_host_id': '3', 'date__gt': '2017-08-10'}

    # print('===models_class.objects.filter(**filter_conditions)===',models_class.objects.filter(**filter_conditions))
    # ===models_class.objects.filter(**filter_conditions)=== <QuerySet [<SessionTrack: 1-zhangju>, <SessionTrack: 2-zhangju>, <SessionTrack: 3-zhangju>,]

    return models_class.objects.filter(**filter_conditions)


class AuditLogTableHandler(object):
    def __init__(self, request, model_class, admin_class, query_sets, order_res):
        self.request = request
        self.model_class = model_class
        # self.admin_class = admin_class
        self.query_sets = query_sets
        # self.choice_fields = admin_class.choice_fields
        self.fk_fields = admin_class.fk_fields

        self.list_display = admin_class.list_display
        # self.list_filter = self.get_list_filter(admin_class.list_filter)  # 不需要过滤信息，所有可以不用启用添加的。

        # for order by
        self.orderby_field = order_res[1]
        self.orderby_col_index = order_res[2]

        # print("list display:",admin_class.list_display)

        #for dynamic display
        self.dynamic_fk = getattr(admin_class,'dynamic_fk') if \
                hasattr(admin_class, 'dynamic_fk') else None
        self.dynamic_list_display = getattr(admin_class,'dynamic_list_display') if \
            hasattr(admin_class,'dynamic_list_display') else ()
        self.dynamic_choice_fields = getattr(admin_class,'dynamic_choice_fields') if \
            hasattr(admin_class,'dynamic_choice_fields') else ()

        #for m2m fields
        self.m2m_fields  = getattr(admin_class,'m2m_fields') if \
            hasattr(admin_class,'m2m_fields') else ()

    def get_list_filter(self, list_filter):
        filters = []
        # print("list filters",list_filter)
        for i in list_filter:
            col_obj = self.model_class._meta.get_field(i)
            # print("=====col obj=====", col_obj )
            # =====col obj===== repository.SessionTrack.user
            # =====col obj===== repository.SessionTrack.bind_host
            # =====col obj===== repository.SessionTrack.date

            # print("=====col obj=====", col_obj.deconstruct() )
            # =====col obj===== ('user', 'django.db.models.ForeignKey', [], {'on_delete': <function CASCADE at 0x000001C93B5A0048>, 'to': 'repository.UserProfile'})
            # =====col obj===== ('bind_host', 'django.db.models.ForeignKey', [], {'on_delete': <function CASCADE at 0x000001C93B5A0048>, 'to': 'repository.BindHosts'})
            # =====col obj===== ('date', 'django.db.models.DateTimeField', [], {'auto_now_add': True})

            data = {
                'verbose_name': col_obj.verbose_name,
                'column_name': i,
                # 'choices' : col_obj.get_choices()
            }

            if col_obj.deconstruct()[1] not in ('django.db.models.DateTimeField',):
                try:
                    choices = col_obj.get_choices()
                    print('===1.choice===',choices)

                    # ===1.choice=== [('', '---------'), (1, '1779038564@qq.com')]
                    # ===1.choice=== [('', '---------'), (1, '192.168.3.100-root(ssh/password)123qwe'), (2, '10.0.133.246-root(ssh/password)111qqq,,,'),]

                except AttributeError as e:  # get_choices 处理没有 多个选项的时候。
                    choices_list = col_obj.model.objects.values(i).annotate(count=Count(i))
                    print('===2.choices_list===', choices_list)
                    choices = [[obj[i], obj[i]] for obj in choices_list]
                    print('===3.choice===',choices)
                    choices.insert(0, ['', '----------'])


            else:  # 特殊处理datefield 和 DateTimeField  此处请注意的是 数据库里models 的字段的类型。datefield 或者 DateTimeField
                today_obj = timezone.datetime.now()
                choices = [
                    ('', '---------'),
                    (today_obj.strftime("%Y-%m-%d"), '今天'),
                    ((today_obj - timezone.timedelta(days=7)).strftime("%Y-%m-%d"), '过去7天'),
                    ((today_obj - timezone.timedelta(days=today_obj.day)).strftime("%Y-%m-%d"), '本月'),
                    ((today_obj - timezone.timedelta(days=90)).strftime("%Y-%m-%d"), '过去3个月'),
                    ((today_obj - timezone.timedelta(days=180)).strftime("%Y-%m-%d"), '过去6个月'),
                    ((today_obj - timezone.timedelta(days=365)).strftime("%Y-%m-%d"), '过去1年'),
                    ((today_obj - timezone.timedelta(seconds=time.time())).strftime("%Y-%m-%d"), 'ALL'),
                ]
            data['choices'] = choices
            # print(choices)
            # handle selected data
            if self.request.GET.get(i):
                data['selected'] = self.request.GET.get(i)
            filters.append(data)

        print(filters)

        # [
        #   {
        #    'column_name': 'user', 'verbose_name': 'user', 'choices': [('', '---------'), (1, '1779038564@qq.com')]
        #   },
        #
        #   {
        #        'column_name' : 'bind_host',
        #        'verbose_name': 'bind host',
        #        'choices': [
        #                    ('', '---------'), (1, '192.168.3.100-root(ssh/password)'), (2, '10.0.133.246-root(ssh/password)'),
        #                    (3, '192.168.3.101-root(ssh/password)'), (4, '192.168.3.102-root(ssh/password)')
        #                    ]
        #    },
        #
        #    {
        #     'column_name': 'date',
        #     'verbose_name': 'date',
        #     'choices': [
        #                 ('', '---------'), ('2017-08-17', '今天'), ('2017-08-10', '过去7天'), ('2017-07-31', '本月'),
        #                 ('2017-05-19', '过去3个月'), ('2017-02-18', '过去6个月'), ('2016-08-17', '过去1年'), ('1970-01-01', 'ALL')
        #                ]
        #    }
        #  ]

        return filters

def table_audit_cmd_filter(request, model_admin, models_class):
    '''根据过滤条件查找数据'''

    print(model_admin.list_filter)
    filter_conditions = {}
    for condition in model_admin.list_filter:  # 如果 filter 里不是空的,一定是加了附加条件。所以会
        if request.GET.get(condition):
            filed_type_name = models_class._meta.get_field(condition).__repr__()
            print('==filed_type_name==',filed_type_name)

            if 'ForeignKey' in filed_type_name:
                filter_conditions['%s_id' % condition] = request.GET.get(condition)
            elif 'DateField' in filed_type_name or 'DateTimeField' in filed_type_name:
                filter_conditions['%s__gt' % condition] = request.GET.get(condition)
            else:
                filter_conditions[condition] = request.GET.get(condition)

    # print("=====filter conditons======", filter_conditions)
    # 结果：
    # =====filter conditons====== {'bind_host_id': '3', 'date__gt': '2017-08-10'}
    return models_class.objects.filter(**filter_conditions)

